package freemind.controller;

import freemind.controller.NodeAdapterBase;
import freemind.main.XMLElement;
import freemind.main.XMLParseException;


public class XMLMindMapLoadProtocol extends XMLProtocolBase implements XMLProtocol {

	XMLElement request;
	XMLElement response;
	
	XMLElement arvore;
	
	public XMLMindMapLoadProtocol(int eneg_modulo) {
		super(XMLProtocol.LOAD,eneg_modulo);
		
		arvore = new XMLElement();
		arvore.setName("arvore");
	}
	
	public void makeRequest(int rootId){
		super.makeRequest();
		
		request = super.getXML();
		
			XMLElement rootIdElement = new XMLElement();
			rootIdElement.setName("root_id");
			rootIdElement.setContent( String.valueOf(rootId) );
		
		request.addChild( rootIdElement );
	}
	
	public XMLElement getXML(){

		if( this.getOperacao() == XMLProtocol.REQUEST ){
//			System.out.println("REQUEST LOAD: " + request.toString());
			return request;
		}
		else if( this.getOperacao() == XMLProtocol.RESPONSE ){
//			System.out.println("RESPONSE LOAD: " + response.toString());
			return response;
		}
		
		return null;
	}
	
	public XMLElement readXML(String s) throws XMLParseException{
		XMLElement newElement = super.readXML(s);
		
		if( this.getOperacao()==XMLProtocol.REQUEST ){
			this.request = newElement;
		}
		else if( this.getOperacao() == XMLProtocol.RESPONSE ){
			this.response = newElement;
		}				
		
		return newElement;
	}			
	
	public NodeAdapterBase getRoot(){
		XMLElement meta = (XMLElement) response.getChildren().get(0);	
		
		XMLElement arvore = (XMLElement) response.getChildren().get(1);
		NodeAdapterBase root;
		
		XMLElement noElement = (XMLElement) arvore.getChildren().get(0);
		root = getBeanFromXML(noElement);
		root.setMetaDados(meta);
		
		return root;
	}

	private NodeAdapterBase getBeanFromXML(XMLElement noElement){
		XMLElement filhosElement = (XMLElement) noElement.getChildren().get(2);
		
		NodeAdapterBase na = NodeAdapterBase.getAdapterFromEnegModulo(this.getEnegModulo() );
		na.getBeanFromXML(noElement);
				
		for(Object o: filhosElement.getChildren()){
			XMLElement child = (XMLElement) o;
			na.addChild( ( getBeanFromXML(child) ) );
		}	
		
		return na;
	}
}